//
//  UserManager.m
//  CKApp
//
//  Created by CC on 2020/8/25.
//  Copyright © 2020 This Moment. All rights reserved.
//

#import "UserManager.h"
#import "LcFoundation.h"
#import "NameCard.h"
#import "AppDelegate.h"
#import "LcNotificationCenter.h"
#import "NotificationHint.h"

@implementation UserManagerModel

- (BOOL)isLogined {
  return self.me != nil && self.clientToken.length > 0;
}

@end

@interface UserManager()
@property(nonatomic, strong) LcJson* lcJson;
@property(nonatomic, strong) LcPersistenceCenter* persistenceCenter;
@property(nonatomic, strong) UserManagerModel* model;
@end

@implementation UserManager

static LcPersistenceMeta* USER_MANAGER_MODEL_META;

+ (void)initialize {
  if (self == [UserManager self]) {
    USER_MANAGER_MODEL_META =
    [LcPersistenceMeta persistenceMetaWithFileName:NSStringFromClass(UserManagerModel.class)
                                              type:NSStringFromClass(UserManagerModel.class)
                                       compressing:YES
                                        encrypting:NO];
  }
}

- (void)internalInit {
  self.lcJson = [LcJson sharedInstance];
  self.persistenceCenter = [LcPersistenceCenter sharedInstance];
  self.model = [self.persistenceCenter objectForPersistenceMeta:USER_MANAGER_MODEL_META];
  if (self.model == nil) {
    self.model = [[UserManagerModel alloc] init];
  }
}

- (void)didLogin:(NameCard*)me
     clientToken:(NSString*)clientToken {
  self.model.me = me;
  self.model.clientToken = clientToken;
  [self saveUserManagerModel];
  [[LcNotificationCenter sharedInstance] sendNotification:NOTIFICATION_USER_DID_LOGIN];
}

- (void)updateMe:(NameCard*)me {
  self.model.me = me;
  [self saveUserManagerModel];
}

- (NameCard*)me {
  if (self.isLogined) {
    return [self.lcJson jsonCopy:self.model.me];
  }
  return nil;
}

- (NSString*)clientToken {
  return self.model.clientToken;
}

- (NSString*)meId {
  return self.model.me.id;
}

- (BOOL)isLogined {
  return [self.model isLogined];
}

- (void)saveUserManagerModel {
  [self.persistenceCenter saveObject:self.model forPersistenceMeta:USER_MANAGER_MODEL_META];
}

- (void)didLogOut {
  [self.persistenceCenter remove:USER_MANAGER_MODEL_META];
  self.model = [[UserManagerModel alloc] init];
  [[LcNotificationCenter sharedInstance] sendNotification:NOTIFICATION_USER_DID_LOGOUT];
}

@end

